package com.techsen.tsweb.sys.security;

import org.apache.shiro.authz.Permission;

/**
 * ACL权限<br/>
 * 资源类型:资源ID:访问控制码
 */
public class AclPermission implements Permission {

    public static final String WILDCARD_TOKEN = "*";
    public static final String DIVIDER_TOKEN = ":";
    public static final Integer NONE_PERMISSION_TOKEN = 0x0;
    public static final Integer ALL_PERMISSION_TOKEN = 0xFFFFFFFF;
    
    /**
     * 资源类型
     */
    private String resourceType = WILDCARD_TOKEN;
    
    /**
     * 资源所属组
     */
    private String resourceGroup = WILDCARD_TOKEN;
    
    /**
     * 访问控制码
     */
    private Integer aclCode = NONE_PERMISSION_TOKEN;

    public AclPermission() {
    }

    public AclPermission(String resourceType, String resourceGroup, Integer aclCode) {
        this.resourceType = resourceType;
        this.resourceGroup = resourceGroup;
        this.aclCode = aclCode;
    }

    public String toString() {
        return resourceType + DIVIDER_TOKEN + resourceGroup
                + DIVIDER_TOKEN + aclCode;
    }

    @Override
    public boolean implies(Permission p) {
        if (p instanceof AclPermission) {
            AclPermission other = (AclPermission) p;
            if (WILDCARD_TOKEN.equals(this.resourceType)
                    || this.resourceType.equalsIgnoreCase(other.resourceType)) {
                if (WILDCARD_TOKEN.equals(this.resourceGroup)
                        || this.resourceGroup.equalsIgnoreCase(other.resourceGroup)) {
                    return (this.aclCode & other.aclCode) > 0;
                }
            }
        }
        return false;
    }

    public String getResourceType() {
        return resourceType;
    }

    public AclPermission setResourceType(String resourceType) {
        this.resourceType = resourceType;
        return this;
    }

    public String getResourceGroup() {
        return resourceGroup;
    }

    public AclPermission setResourceGroup(String resourceGroup) {
        this.resourceGroup = resourceGroup;
        return this;
    }

    public Integer getAclCode() {
        return aclCode;
    }

    public AclPermission setAclCode(Integer aclCode) {
        this.aclCode = aclCode;
        return this;
    }

}
